package com.house365.updown.download;

import java.util.HashMap;
import java.util.Map;

import android.content.Context;

import com.house365.core.constant.CorePreferences;
import com.house365.updown.download.HttpDownloaderManager.DownloadListener;

/**
 * @author py
 * @date 2013-5-10
 * @comment
 */
public class Downloader {
	private Context context;

	
	private DownloaderDBService dbService;

	private Map<String,DownloadCompleteListener> onDownloadCompleteListeners;;
	
	HttpDownloaderManager httpDownloaderManager ;
	

	public Downloader(Context context) {
		this.context = context;
		dbService = DownloaderDBService.getDBService(context);
		httpDownloaderManager = new HttpDownloaderManager(context);
		httpDownloaderManager.setDownloadListener(new DownloadListener() {
			
			@Override
			public void onError(long id) {
				CorePreferences.DEBUG("httpDownloaderManager.onError..");
				DFile dFile = dbService.getDFileByReferId(id);
				if (dFile != null) {
					//下载失败
					erroredFile(dFile);
						if(onDownloadCompleteListeners != null){
							DownloadCompleteListener downloadCompleteListener = onDownloadCompleteListeners.get(dFile.getOuterid());
							if(downloadCompleteListener!= null){
								downloadCompleteListener.onError(dFile);
								//执行完比以后，直接移除该方法
								onDownloadCompleteListeners.remove(dFile.getOuterid());
							}
							
						}
				
				}
			}
			
			@Override
			public void onComplete(long id) {
				CorePreferences.DEBUG("httpDownloaderManager.onComplete..");
				DFile dFile = dbService.getDFileByReferId(id);
				if (dFile != null) {
					getDownloadingStatus(dFile);
						// 下载成功了
						completedFile(dFile);
						if(onDownloadCompleteListeners != null){
							DownloadCompleteListener downloadCompleteListener = onDownloadCompleteListeners.get(dFile.getOuterid());
							if(downloadCompleteListener!= null){
								downloadCompleteListener.onComplete(dFile);
								//执行完比以后，直接移除该方法
								onDownloadCompleteListeners.remove(dFile.getOuterid());
							}
						}
				}
			}
		});
		DFile dfile = dbService.getDownloadingDFile();
		if (dfile != null) {
			// 有正在下载,将状态置为等待
			dbService.moveDonwloadingToQueue(dfile);
		}
		startNewDownFile();
	}

	

	public void destory() {
		DFile dfile = dbService.getDownloadingDFile();
		if (dfile != null) {
			// 有正在下载,将状态置为等待
			dbService.moveDonwloadingToQueue(dfile);
		}
	}
	
	/**
	 * 添加一个下载任务
	 * @param dFile
	 */
	public void addDFile(DFile dFile) {
		CorePreferences.DEBUG("addDFile..");
		dbService.saveDFile(dFile, DOWN_STAUTS_QUEUE);
		startNewDownFile();
	}

	/**
	public void setPriority(String id, int priority) {
		DFile dFile = getDFileQueueByOuterId(id);
		dFile.setPriority(priority);
		Collections.sort(dFilesQueue, new Comparator<DFile>() {
			@Override
			public int compare(DFile object1, DFile object2) {
				return object1.getPriority() - object2.getPriority();
			}
		});
	}

	public void increasePriority(String id) {
		DFile dFile = getDFileQueueByOuterId(id);
		int i = dFile.getPriority() + 1;
		if (i > 10) {
			i = 10;
		}
		dFile.setPriority(i);
		Collections.sort(dFilesQueue, new Comparator<DFile>() {
			@Override
			public int compare(DFile object1, DFile object2) {
				return object1.getPriority() - object2.getPriority();
			}
		});
	}

	public void decreasePriority(String id) {
		DFile dFile = getDFileQueueByOuterId(id);
		int i = dFile.getPriority() - 1;
		if (i < 1) {
			i = 1;
		}
		dFile.setPriority(i);
		Collections.sort(dFilesQueue, new Comparator<DFile>() {
			@Override
			public int compare(DFile object1, DFile object2) {
				return object1.getPriority() - object2.getPriority();
			}
		});
	}
	*/

	public void startNewDownFile() {
		synchronized (this) {
			CorePreferences.DEBUG("startNewDownFile..");
		DFile dFile = dbService.getDownloadingDFile();
		if (dFile  == null) {
			DFile toDownDFile = dbService.getFirstQueueDFile();
			if(toDownDFile!= null){
				long id = downFile(toDownDFile);
				toDownDFile.setReferId(id);
				dbService.moveQueueToDonwloading(toDownDFile);
			}
			
		}
		}
	}

	private long downFile(DFile dFile) {
		synchronized (this) {
			//启动一个下载任务
			CorePreferences.DEBUG("downFile..");
			return httpDownloaderManager.downLoadFile(dFile.getRemoteFileUri(), dFile.getLocalFileUri());
		}
	}

	public void getDownloadingStatus(DFile dFile) {
		synchronized (this) {
			
			DownloaderInfo downInfo =  httpDownloaderManager.getDownloaderInfo(dFile.getReferId());
			if(downInfo != null){
				dFile.setDownSize(downInfo.getNowSize());
				dFile.setStatus(downInfo.getStatus());
				if (dFile.getTotalSize() <= 0) {
					// 查询下载文件总大小
					long totalSize =downInfo.getMaxSize();
					if(totalSize>0){
						dFile.setTotalSize(totalSize);	
					}
					
					dbService.updateDownloadingInfo(dFile);
				}
			}
		

		}
	}

	public void removeFileByOuterId(String outerid) {
		synchronized (this) {
			DFile dFile = dbService.getDFileByOuterId(outerid);
			if(dFile!= null){
				if (dFile.getType() == DOWN_STAUTS_DOWNING) {
					//如果正在下载，移动到待下载区
					dbService.moveDonwloadingToQueue(dFile);
					httpDownloaderManager.cancelDownload(dFile.getReferId());
					startNewDownFile();
				}else if(dFile.getType() == DOWN_STAUTS_QUEUE){
					//直接移除
					dbService.removeDFileOuterId(dFile.getOuterid());
				}
					
			}
			

		}
	}
	public DFile getDownloadingDFile() {
		return dbService.getDownloadingDFile();
	}

	public void completedFile(DFile dFile) {
		synchronized (this) {
			// 下载成功了
			dbService.moveDonwloadingToDownloaded(dFile);
			// 添加下一个下载任务
			startNewDownFile();
		}
	}
	public void erroredFile(DFile dFile) {
		synchronized (this) {
			// 下载失败,移除到待下载区域
			dbService.moveDonwloadingToQueue(dFile);
			// 添加下一个下载任务
			startNewDownFile();
		}
	}
	// public int getCount() {
	// return dFiles == null ? 0 : dFiles.size();
	// }

	public static final int DOWN_STAUTS_QUEUE = 1;
	public static final int DOWN_STAUTS_DOWNING = 2;
	public static final int DOWN_STAUTS_DOWNED = 3;
	public static final int DOWN_STAUTS_UNKONW = -1;

	


	public int getStatusByOuterId(String outerid) {
		DFile dFile = dbService.getDFileByOuterId(outerid);
		if(dFile != null){
			return dFile.getType();
		}else{
			return DOWN_STAUTS_UNKONW;
		}
	}
	public DFile getDFileByOuterId(String outerid){
		return dbService.getDFileByOuterId(outerid);
	}
	public boolean isDowning(){
		if(getDownloadingDFile()!= null){
			return true;
		}
		return false;
	}
	public void addDownloadCompleteListener(String key,DownloadCompleteListener listener){
		if(onDownloadCompleteListeners == null){
			onDownloadCompleteListeners = new HashMap<String,DownloadCompleteListener>();
		}
		onDownloadCompleteListeners.put(key,listener);
	}
	public interface DownloadCompleteListener{
		public void onComplete(DFile dFile);
		public void onError(DFile dFile);
	}
}
